import React, { Component } from 'react';
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import debounce from 'lodash.debounce'
import PropTypes from 'prop-types';
import htmlToDraft from 'html-to-draftjs';


export default class RichTextEditor extends Component {
  state = {
    editorState: EditorState.createEmpty(),
  }

  static propTypes = {
    detail:PropTypes.string
  }

  // 暴露一个方法给父组件获取到HTML的内容
  getHtmlDetail = () => (draftToHtml(convertToRaw(this.state.editorState.getCurrentContent())))

  onEditorStateChange =debounce((editorState) => {
    this.setState({
      editorState,
    });
  },200)

  uploadImageCallBack = (file) => {
    return new Promise(
      (resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('POST', '/manage/img/upload');
        xhr.setRequestHeader('Authorization', 'Client-ID XXXXX');
        const data = new FormData();
        data.append('image', file);
        xhr.send(data);
        xhr.addEventListener('load', () => {
          const response = JSON.parse(xhr.responseText);
          console.log(response)
          resolve(response);
        });
        xhr.addEventListener('error', () => {
          const error = JSON.parse(xhr.responseText);
          reject(error);
        });
      }
    );
  }

  UNSAFE_componentWillMount(){
    if(this.props.detail){
      console.log(this.props.detail)
    // 将父组件传递过来的detail转化为 draftToHtml
    const detail = this.props.detail
    const contentBlock = htmlToDraft(detail);
    if (contentBlock) {
      const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
      const editorState = EditorState.createWithContent(contentState);
      this.setState({
        editorState,
      })
    }
    }
  }

  render() {
    const { editorState } = this.state;
    return (
      <div>
        <Editor
          editorStyle={{border:'1px solid #000',height:200, padding:'0 10px'}}
          editorState={editorState}
          onEditorStateChange={this.onEditorStateChange}
          toolbar={{
            image: { uploadCallback: this.uploadImageCallBack, alt: { present: true, mandatory: true } },
          }}
        />
      </div>
    );
  }
}

/**
 * 
 * 1. 找到富文本编译器的模板
 * 2. 修改样式 editorStyle
 * 3. 定义一个方法提供给父组件获取HTML的内容
 * getHtmlDetail()
 * 
 * 
 */
